import { login } from '@/api/login.js'
import router from '@/router'
import { getProfile, getToken, setProfile, setToken } from '@/utils/auth'
import { Message } from 'element-ui'
const state = {
  token: getToken() || '',
  user: getProfile() || ''
}

const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setProfile(state, value) {
    state.user = value
    setProfile(value)
  }
}

const actions = {
  async login(context, payload) {
    try {
      const res = await login(payload)
      if (res.code === 1) {
        Message.error(res.msg)
      } else {
        context.commit('setToken', res.data.token.token)
        context.commit('setProfile', res.data.user)
        Message.success('登录成功')
        router.push('/')
        console.log(res)
      }
    } catch (e) {
      console.dir(e)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
